package udp_tcp.view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ChatFrame extends JFrame {
    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
    private JList<String> userList;

    public ChatFrame(String title) {
        super(title);
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 聊天区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        add(new JScrollPane(chatArea), BorderLayout.CENTER);

        // 用户列表
        userList = new JList<>();
        add(new JScrollPane(userList), BorderLayout.EAST);

        // 消息输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        messageField = new JTextField();
        sendButton = new JButton("发送");

        inputPanel.add(messageField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);
    }

    public void setSendAction(Action action) {
        sendButton.setAction(action);
        messageField.addActionListener(action);
    }

    public String getMessage() {
        String msg = messageField.getText();
        messageField.setText("");
        return msg;
    }

    public void appendMessage(String message) {
        chatArea.append(message + "\n");
    }

    public void setUserList(String[] users) {
        userList.setListData(users);
    }
}